﻿using System;
using System.Drawing;
using Space.Library;
using Space.Library.Extensions;
using Space.Model.Entity;

namespace Space.Model.Fsm
{
    /// <summary>
    /// Moves the ship to the target square. 
    /// </summary>
    public class MoveToTargetState : IState<Ship>
    {
        public bool AcceptInput { get { return false; } }

        public Ship Owner { get; set; }
        private readonly Point _targetCoords;

        private Vector2D _direction;
        private Vector2D _target;
        private float _stopDist;

        public MoveToTargetState(Point targetCoords)
        {
            _targetCoords = targetCoords;
        }

        public void Enter()
        {
            _target = _targetCoords.AsVectorToMid();
            var directionVector = _target - Owner.BoardCoords.AsVectorToMid();

            _direction = directionVector.ToUnitVector();
            _stopDist = _direction.Length() + 0.1f;
        }

        public void Execute(long timestep)
        {
            if ((_target - Owner.Pos).Length() <= _stopDist)  // done
            {
                Owner.SetPosition(_targetCoords);
                Owner.Fsm.ChangeState(new NothingState<Ship>());
                return;
            }

            var movement = _direction * timestep * 0.1f;
            Owner.Move(movement);
        }

        public void Exit()
        {
            // Clear steering
        }
    }
}
